package com.lyxy.filter;

import com.alibaba.fastjson.JSONObject;
import com.lyxy.pojo.Result;
import com.lyxy.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 *
 * @ClassName LoginCheckFilter
 * @Description TODO
 * 登录拦截器
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

/**
 * 1.获取url
 */
        String url = request.getRequestURL().toString();
/**
 *  2.判断是否为登录操作(login) 若是的话放行
 */
        if (url.contains("login")) {
            log.info("登陆操作");
            filterChain.doFilter(request, response);
            return;
        }

/**
 * 3.获取请求头中的令牌,若不存在则跳转到登录界面
 */
        String token = request.getHeader("token");

//      判断令牌是否存在
        if (!StringUtils.hasLength(token)) {
            log.info("令牌为空，返回登录信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;

        }

//        解析令牌是否有效
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

/**
 * 4.令牌合法放行
 */
        log.info("令牌合法，放行");
        filterChain.doFilter(request, response);


    }


}
